/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-16 下午3:46
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment.Consulation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.ConsulationDeatilActivity;
import com.example.dqhl.jdmetro.adapter.consulation.ConsulationDataAdapter;
import com.example.dqhl.jdmetro.adapter.consulation.ConsulationHotNewsAdpater;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationBanner;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationData;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationHotNews;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.utils.recycleview.ConsulationRecycleViewLayoutManager;
import com.example.dqhl.jdmetro.utils.recycleview.ConsulationRecycleviewDecoration;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:资讯 第一个Fragment
 * autour:guanluocang
 * date:17/6/16 15:46
 */
public class ConsultationFirstFragment extends BaseFragment {

    @Bind(R.id.consulation_first_refresh_layout)
    TwinklingRefreshLayout consulation_first_refresh_layout;
    private Context context;

    //    @Bind(R.id.consulationScrollView)
//    ConsulationScrollView consulationScrollView;
    private int mScrollY;
    private int mScrollX;
    //轮播图
    @Bind(R.id.sliderLayout)
    SliderLayout sliderLayout;
    @Bind(R.id.custom_indicator)
    PagerIndicator custom_indicator;
    List<ConsulationBanner> bannerList = new ArrayList<>();

    //热点要闻
    @Bind(R.id.rv_consulationHotNews)
    RecyclerView rv_consulationHotNews;
    private List<ConsulationHotNews> hotNewsList = new ArrayList<>();
    private ConsulationHotNewsAdpater hotNewsAdpater;

    //资讯列表
    @Bind(R.id.rv_consulationList)
    RecyclerView rv_consulationList;
    private List<ConsulationData.DataBean> consulationDataList = new ArrayList<>();
    private List<ConsulationData.DataBean.PicAllBean> pic_allList = new ArrayList<>();
    private ConsulationDataAdapter consulationDataAdapter;
    private int page = 1;

    @Override
    public View initView(LayoutInflater inflater) {
        context = getActivity();
        rootView = inflater.inflate(R.layout.fragment_consultation_first, null);
        //让其获取焦点
//        rootView.setFocusable(true);
//        rootView.setFocusableInTouchMode(true);
//        rootView.requestFocus();
        ButterKnife.bind(this, rootView);
        registerBroadcastReceiver();
        //热点要闻
        ConsulationRecycleViewLayoutManager linearLayoutManager_hotNews = new ConsulationRecycleViewLayoutManager(getActivity());
        linearLayoutManager_hotNews.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_consulationHotNews.setLayoutManager(linearLayoutManager_hotNews);
        rv_consulationHotNews.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));


        //资讯列表
        ConsulationRecycleViewLayoutManager linearLayoutManager_list = new ConsulationRecycleViewLayoutManager(getActivity());
        linearLayoutManager_list.setOrientation(LinearLayoutManager.VERTICAL);
        rv_consulationList.setLayoutManager(linearLayoutManager_list);
        rv_consulationList.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));

        //     是为了确保mNoHorizontalScrollView他的子孙不能获得焦点
//        consulationScrollView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

        return rootView;
    }

    @Override
    public void initData() {
        rv_consulationHotNews.setAdapter(hotNewsAdpater = new ConsulationHotNewsAdpater(context));
        rv_consulationList.setAdapter(consulationDataAdapter = new ConsulationDataAdapter(context));
        ProgressLayout headerView = new ProgressLayout(getActivity());
        consulation_first_refresh_layout.setHeaderView(headerView);
        consulation_first_refresh_layout.setOverScrollRefreshShow(false);
        getBannerData();
        getHotNews();
        getData(page);
        rv_consulationList.addItemDecoration(new ConsulationRecycleviewDecoration(getActivity(), ConsulationRecycleviewDecoration.VERTICAL_LIST));

    }


    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_LOGIN_SUCCESS)) {
                user = (User) intent.getExtras().get("user");
                Dlog.e(user.toString());
            } else if (action.equals(Constant.ACTION_LOGOUT_SUCCESS)) {
                user = null;
            }
        }
    };

    /**
     * 注册广播接收者
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }

    @Override
    public void initListener() {
        consulation_first_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                getBannerData();
                getHotNews();
                getData(page);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                loadMoreList(page);
                refreshLayout.finishLoadmore();
            }
        });
    }

    /**
     * 获取轮播图数据
     */
    private void getBannerData() {
        RequestParams params = new RequestParams(Config.consulation_banner);
        x.http().get(params, new Callback.CacheCallback<String>() {
            @Override
            public boolean onCache(String result) {
                return false;
            }

            @Override
            public void onSuccess(String result) {
                Dlog.e("banner数据" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    bannerList = JSON.parseArray(data, ConsulationBanner.class);
                    for (int i = 0; i < bannerList.size(); i++) {
                        //新建三个展示View，并且添加到SliderLayout
                        TextSliderView tsv = new TextSliderView(getActivity());
                        tsv.description(bannerList.get(i).getTitle()).image(Config.pic_base_url + bannerList.get(i).getPic());
                        final int finalI = i;
                        tsv.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                            @Override
                            public void onSliderClick(BaseSliderView slider) {
                                if (user != null) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("info_id", bannerList.get(finalI).getInfo_id());
                                    JumpItent.jump(getActivity(), ConsulationDeatilActivity.class, bundle);
                                } else {
                                    Toastutils.show("请先登录");
                                }
//                                Toast.makeText(getActivity(), bannerList.get(finalI).getTitle(), Toast.LENGTH_SHORT).show();
                            }
                        });

                        sliderLayout.addSlider(tsv);
                    }

                    //对SliderLayout进行一些自定义的配置
                    sliderLayout.setCustomAnimation(new DescriptionAnimation());
                    //设置滑动的动画
                    sliderLayout.setPresetTransformer(SliderLayout.Transformer.Tablet);
                    sliderLayout.setDuration(3000);
                    //      sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
                    sliderLayout.setCustomIndicator(custom_indicator);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 获取热点要闻
     */
    private void getHotNews() {
        RequestParams params = new RequestParams(Config.consulation_hotNews);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("热点新闻" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    hotNewsList = JSON.parseArray(data, ConsulationHotNews.class);
                    hotNewsAdpater.refresh_newHots(hotNewsList);
                    hotNewsAdpater.setOnItemClickListener(new ConsulationHotNewsAdpater.onItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (user != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("info_id", hotNewsList.get(position).getInfo_id());
                                JumpItent.jump(getActivity(), ConsulationDeatilActivity.class, bundle);
                            } else {
                                Toastutils.show("请先登录");
                            }
                        }
                    });
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取列表
     */
    public void getData(int pages) {
        RequestParams params = new RequestParams(Config.consulation_list);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("资讯列表" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    ConsulationData consulationData = new Gson().fromJson(result, ConsulationData.class);
                    consulationDataList = consulationData.getData();
//                    rv_consulationList.setAdapter(consulationDataAdapter = new ConsulationDataAdapter(context,consulationDataList));
                    consulationDataAdapter.refresh_list(consulationDataList);
                    consulationDataAdapter.setOnItemClickListener(new ConsulationDataAdapter.onItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (user != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("info_id", consulationDataList.get(position).getInfo_id());
                                JumpItent.jump(getActivity(), ConsulationDeatilActivity.class, bundle);
                            } else {
                                Toastutils.show("请先登录");
                            }

                        }
                    });
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 加载更多
     */
    public void loadMoreList(int pages) {
        RequestParams params = new RequestParams(Config.consulation_list);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("资讯列表" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    ConsulationData consulationData = new Gson().fromJson(result, ConsulationData.class);
                    consulationDataList.addAll(consulationData.getData());
                    consulationDataAdapter.refresh_list(consulationDataList);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 在界面切换的时候会调用这个方法
     * true 表示可见
     * FALSE 表示不可见
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {//表示界面可见
//            if (consulationScrollView != null) {// 之所以判断是否为空，
//                //                mNoHorizontalScrollView.setDescendantFocusability(ViewGroup
//                // .FOCUS_BLOCK_DESCENDANTS);
//            }

        } else {// 表示界面不可见
//            if (consulationScrollView != null) {
//                mScrollX = consulationScrollView.getScrollX();
//                mScrollY = consulationScrollView.getScrollY();
//
//            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }

}
